package com.oj.service.impl;

import com.oj.entity.Message;
import com.oj.entity.Problem;
import com.oj.entity.User;
import com.oj.mapper.MessageMapper;
import com.oj.service.MessageService;
import com.oj.service.UserService;
import com.oj.util.Html2Text;
import com.oj.util.IpUtil;
import com.oj.util.MyFreeMarker;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserService userService;

    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;

    @Override
    @Transactional
    public List<Message> search(String q, Integer limit, Integer offset) {
        Map param = new HashMap();
        param.put("defunct", 'N');
        param.put("q", q);
        param.put("limit", limit);
        param.put("offset", offset);
        return messageMapper.search(param);
    }
    public void topTopicsGenerator() {
        try {
            Map param = new HashMap();
            param.put("queryRootMessages", 1);
            List<Message> latestMessages = messageMapper.queryList(param);

            for(Message m_:latestMessages){
                if (m_.getTitle().length() > 50) {
                    m_.setTitle(m_.getTitle().subSequence(0, 50)+"...");
                }
                m_.setUser(userService.query(m_.getCreate_user()));

                String bufString = new String();
                bufString = Html2Text.RemoveHtml(((m_.getContent().length()>2000)?(m_.getContent()).substring(0, 2000):m_.getContent()));
                m_.setContent_abstract(((bufString.length()>500)?(bufString).substring(0, 500)+"...":bufString));
                int newlineIndex = m_.getContent_abstract().indexOf("\n");
                if (newlineIndex != -1) {
                    m_.setContent_abstract(m_.getContent_abstract().substring(0, newlineIndex));
                }
            }
            Map map = new HashMap();
            map.put("topics", latestMessages);
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("freemarker/latesttopic.ftl");
            MyFreeMarker.generator(template, "latesttopic.html",map);
            log.info("latestTopics generator run.");
        }catch (Exception e) {
            log.error("latestTopics exception:" + e.toString());
        }
    }
}
